package com.imoresoft.agile.action;

import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.ambitor.grass.util.data.DataMap;
import com.ambitor.grass.util.data.DatasetList;
import com.ambitor.grass.util.data.IData;
import com.ambitor.grass.util.data.IDataset;
import com.imoresoft.agile.exception.ProException;
import com.imoresoft.agile.property.ProsReader;
import com.imoresoft.agile.top.TopConstants;
import com.imoresoft.agile.top.TopService;
import com.taobao.api.domain.SellerCat;

public class SellerCatsAction extends BaseAction {

	private static final long serialVersionUID = 8189262641616011463L;

	private IDataset sellerCats = new DatasetList();

	@SuppressWarnings("unchecked")
	public String querySellerCats() {
		TopService callService = new TopService(TopConstants.EVN_SWITCH,
				TopConstants.APP_KEY, TopConstants.APP_SECRET);
		logger.info("querySellerCats()开始运行...");
		String nick = pd.getTopNick();
		List<SellerCat> cats = null;
		try {
			cats = callService.getSellerCats(nick);
		} catch (ProException e) {
			logger.warn(nick + "获取分类出现异常");
		}
		if (cats == null || cats.size() == 0)
			return SUCCESS;
		_processSellerCats(cats);
		logger.info("getSellerCats取出" + sellerCats.size() + "条数据.");
		return SUCCESS;
	}

	@SuppressWarnings("unchecked")
	private void _processSellerCats(List<SellerCat> cats) {
		for (SellerCat cat : cats) {
			if (cat.getParentCid().intValue() == 0 && _validateCatName(cat)) { // 遍历第一级类别
				IData data = new DataMap();
				data.put("cid", cat.getCid());
				data.put("name", cat.getName());
				data.put("isLeaf", "1");
				sellerCats.add(data);
				IDataset subCatList = new DatasetList();
				for (SellerCat subCat : cats) {
					if (subCat.getParentCid().intValue() != 0
							&& subCat.getParentCid().equals(cat.getCid())
							&& _validateCatName(cat)) { // 寻找子分类
						IData subData = new DataMap();
						subData.put("cid", subCat.getCid());
						subData.put("name", subCat.getName());
						subData.put("isLeaf", "2");
						subCatList.add(subData);
					}
				}
				if (subCatList.size() > 0) {
					data.put("isLeaf", "0");
					sellerCats.addAll(subCatList);
				}
			}
		}
	}

	private boolean _validateCatName(SellerCat cat) {
		String invalidCats = ProsReader.getString("INVALID_CATS_NAME");
		for (String str : invalidCats.split(",")) {
			if (StringUtils.contains(cat.getName(), str)) {
				return false;
			}
		}
		return true;
	}

	public IDataset getSellerCats() {
		return sellerCats;
	}

	public void setSellerCats(IDataset sellerCats) {
		this.sellerCats = sellerCats;
	}
}
